package org.example.exceptioncatch.demos.controller;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.io.FileInputStream;
import java.util.Date;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
import java.util.concurrent.ThreadPoolExecutor;

@RestController
@RequestMapping("/my")
public class MyController {

    @Autowired
    private ThreadPoolExecutor threadPoolExecutor;

    //主动抛出异常
    @GetMapping("/initiative")
    public String test() {
        Date now = new Date();
        if (true) {
            throw new RuntimeException("主动抛出异常");
        }
        return "test";
    }

    //运行时异常--空指针异常/数组越界异常 等等
    @GetMapping("/runtime")
    public String runtime() {
        String str = null;
        return str.substring(0);
    }

    //受检异常--文件找不到异常 等等
    @GetMapping("/checked")
    public String checked() throws Exception {
        FileInputStream fis = new FileInputStream(new File("111datanew.xlsx"));
        return "checked";
    }

    //try-catch捕获异常
    @GetMapping("/trycatch")
    public String trycatch() {
        try {
            String str = null;
            String substring = str.substring(0);
            System.out.println("substring = " + substring);
        } catch (Exception e) {
        }
        return "trycatch2 请求成功";
    }

    //线程池中的异常
    @GetMapping("/threadpool")
    public String threadpool() throws ExecutionException, InterruptedException {

        MyFuture myFuture = new MyFuture();
        FutureTask<String> futureTask = new FutureTask<>(myFuture);
        threadPoolExecutor.submit(futureTask);

        String s = futureTask.get();//如果是线程池中抛出的异常，这里会被捕获到，当然，前提是用的是Callable接口,并且没有捕获异常
        //如果捕获的话，那么在controller层就不会被捕获，就当正常执行了

        return "threadpool 请求成功";

    }

    //线程池中的异常
    @GetMapping("/threadpool2")
    public String threadpool2() throws ExecutionException, InterruptedException {

        MyFuture2 myFuture = new MyFuture2();
        FutureTask<String> futureTask = new FutureTask<>(myFuture);
        threadPoolExecutor.submit(futureTask);

        Thread.sleep(5000);
        return "threadpool 请求成功";

    }

    @GetMapping("/threadpool3")
    public String threadpool3() {

        MyRunnable myRunnable = new MyRunnable();
        Thread thread = new Thread(myRunnable);

        thread.setUncaughtExceptionHandler((t, e) -> {
            System.out.println("线程池中的异常被捕获到了--2" + e.getMessage());//控制台打印异常信息
        });

        thread.start();

        return "threadpool-myRunnable 请求成功";//这里会依旧被执行

    }


}
